#include "buffer.h"
#include <cassert>
#include <cstring>
#include <iostream>
#include <thread>
#include <vector>
#include <atomic>
#include <unistd.h>

int main() {
    // 创建管道（正确使用读写端）
    int pipeFd[2]; // pipeFd[1] 写端，pipeFd[0] 读端
    if (pipe(pipeFd) == -1) {
        perror("pipe failed");
        return 1;
    }

    Buffer buffer(5); // 假设Buffer构造函数已正确实现

    // 测试写入数据到管道，再从Buffer读取
    const std::string testData = "hello, world!";
    // 写入管道写端
    ssize_t written = write(pipeFd[1], testData.data(), testData.size());
    assert(written == testData.size());

    // 从管道读端读取到Buffer
    int errnoSave = 0;
    ssize_t readLen = buffer.ReadFd(pipeFd[0], &errnoSave); // 传入读端fd
    if (readLen == -1) {
        std::cerr << "ReadFd failed, errno: " << errnoSave << std::endl;
        return 1;
    }

    // 验证数据是否正确
    assert(buffer.ReadableBytes() == testData.size());
    std::string result = buffer.RetrieveAllToStr();
    assert(result == testData);

    std::cout << "Test passed: " << result << std::endl;
    close(pipeFd[0]);
    close(pipeFd[1]);
    return 0;
}